﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using Common.Logging;
using In.Api.Dto.HisWs;
using Newtonsoft.Json;
using OutDbContext;
using Quartz;
using User.Api.HttpClients;

namespace Out.TaskRunner.QuartzJobs
{
    public class TransferDeptAndDoctorInfoJob: IJob
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(TransferDeptAndDoctorInfoJob));

        /// <summary>
        /// 执行成功
        /// </summary>
        public bool IsExecuteSuccess = true;

        /// <summary>
        /// 重试次数
        /// </summary>
        public int RetryTimes = 0;

        public void Execute(IJobExecutionContext context)
        {
            Logger.InfoFormat("Executing job: {0}", context.JobDetail.Key);

            DoTransferDeptAndDoctorInfo();

            while (true)
            {
                if (RetryTimes > 5)
                {
                    IsExecuteSuccess = true;
                    RetryTimes = 0;
                    break;
                }
                
                if (!IsExecuteSuccess)
                {
                    DoTransferDeptAndDoctorInfo();
                }

                RetryTimes++;
            }
        }

        public void DoTransferDeptAndDoctorInfo()
        {
            Console.WriteLine("[{0}] 获取科室和医生信息", DateTime.Now.ToString("MM-dd HH:mm:ss"));

            var deptList = new List<string>();
            var hospitalId = "1036";
            var branchs = new string[] { "0"};
            foreach (var branch in branchs)
            {
                var response4GetDeptInfo = GetDeptsInHosp(branch);
                if (response4GetDeptInfo.ResultCode == "0")
                {
                    foreach (var deptInfoInHosp in response4GetDeptInfo.DeptList)
                    {
                        SaveDept(hospitalId, branch, deptInfoInHosp);
                        deptList.Add(deptInfoInHosp.DeptId);
                        var response4GetDoctorInfo = GetDoctorsInHosp(deptInfoInHosp.DeptId);
                        if (response4GetDoctorInfo.ResultCode == "0")
                        {
                            foreach (var doctorInfoInHosp in response4GetDoctorInfo.DoctorList)
                            {
                                SaveDoctor(hospitalId, branch, doctorInfoInHosp);
                            }

                            using (var ctx = new FsssdqfybjyEntities())
                            {
                                //判断医生是否在院内存在
                                var doctors = ctx.Doctors.Where(x => x.DeptId == deptInfoInHosp.DeptId && x.RecStatus == 1);
                                foreach (var doctor in doctors)
                                {
                                    if (!response4GetDoctorInfo.DoctorList.Any(x => x.DoctorId == doctor.DoctorId))
                                    {
                                        doctor.RecStatus = 2;
                                        doctor.RecDeleteDt = DateTime.Now;
                                    }
                                }
                                ctx.SaveChanges();
                            }
                        }
                        else
                        {
                            IsExecuteSuccess = false;
                            continue;
                        }
                    }
                }
                else
                {
                    IsExecuteSuccess = false;
                }
            }

            if (IsExecuteSuccess)
            {
                //判断科室是否在院内存在
                using (var ctx = new FsssdqfybjyEntities())
                {
                    var depts = ctx.Departs.Where(x => x.RecStatus == 1);
                    foreach (var dept in depts)
                    {
                        if (!deptList.Any(x => x == dept.DeptId))
                        {
                            dept.RecStatus = 2;
                            dept.RecDeleteDt = DateTime.Now;
                        }
                    }
                    ctx.SaveChanges();
                }

                Console.WriteLine("[{0}] 成功获取科室和医生信息", DateTime.Now.ToString("MM-dd HH:mm:ss"));
            }
        }


        public bool SaveDept(string hospitalId, string branch, Response4GetDeptInfoSubDeptInfo deptInfoInHosp)
        {
            using (var ctx = new FsssdqfybjyEntities())
            {
                var deptQuery = ctx.Departs.Where(x => x.DeptId == deptInfoInHosp.DeptId);
                if (deptQuery.Any())
                {
                    var dept = deptQuery.First();
                    dept.DeptId = deptInfoInHosp.DeptId;
                    dept.BranchNo = branch;
                    dept.DeptName = deptInfoInHosp.DeptName;
                    dept.DeptType = deptInfoInHosp.DeptType;
                    //dept.Desc = deptInfoInHosp.Desc;                 
                    dept.Loc = deptInfoInHosp.Loc;
                    dept.RecStatus = 1;
                    dept.ParentId = deptInfoInHosp.ParentId;
                    dept.RecUpdateDt = DateTime.Now;
                    ctx.SaveChanges();
                }
                else
                {
                    var dept = new Depart();
                    dept.DeptId = deptInfoInHosp.DeptId;
                    dept.BranchNo = branch;
                    dept.DeptName = deptInfoInHosp.DeptName;
                    dept.DeptType = deptInfoInHosp.DeptType;
                    dept.Desc = deptInfoInHosp.Desc;
                    dept.Loc = deptInfoInHosp.Loc;
                    dept.RecStatus = 1;
                    dept.RecCreateDt = DateTime.Now;
                    dept.ParentId = deptInfoInHosp.ParentId;
                    ctx.Departs.Add(dept);
                    ctx.SaveChanges();
                }
            }

            return true;
        }

        public bool SaveDoctor(string hospitalId, string branch, Response4GetDoctorInfoSubDoctorInfo doctorInfoInHosp)
        {
            using (var ctx = new FsssdqfybjyEntities())
            {
                var dept = ctx.Departs.FirstOrDefault(x => x.DeptId == doctorInfoInHosp.DeptId && x.RecStatus == 1);
                var doctorQuery = ctx.Doctors.Where(x => x.DoctorId == doctorInfoInHosp.DoctorId && x.DeptId == doctorInfoInHosp.DeptId);
                if (doctorQuery.Any())
                {
                    var doctor = doctorQuery.First();
                    doctor.BranchNo = branch;
                    doctor.DeptId = doctorInfoInHosp.DeptId;
                    doctor.DeptName = dept?.DeptName ?? "";
                    // doctor.Desc = doctorInfoInHosp.Desc;
                    doctor.DoctorId = doctorInfoInHosp.DoctorId;
                    doctor.DoctorName = doctorInfoInHosp.DoctorName;
                    doctor.Fee = "";
                    doctor.Gender = doctorInfoInHosp.Gender;
                    doctor.RecStatus = 1;
                    doctor.Title = doctorInfoInHosp.Title;
                    doctor.RecUpdateDt = DateTime.Now;
                    ctx.SaveChanges();
                }
                else
                {
                    var doctor = new Doctor();
                    doctor.BranchNo = branch;
                    doctor.DeptId = doctorInfoInHosp.DeptId;
                    doctor.DeptName = dept?.DeptName ?? "";
                    doctor.Desc = doctorInfoInHosp.Desc;
                    doctor.DoctorId = doctorInfoInHosp.DoctorId;
                    doctor.DoctorName = doctorInfoInHosp.DoctorName;
                    doctor.Fee = "";
                    doctor.Gender = doctorInfoInHosp.Gender;
                    doctor.Title = doctorInfoInHosp.Title;

                    doctor.RecStatus = 1;
                    doctor.RecCreateDt = DateTime.Now;
                    ctx.Doctors.Add(doctor);
                    ctx.SaveChanges();
                }
            }
            return true;
        }


        public Response4GetDeptInfo GetDeptsInHosp(string branchNo)
        {
            var request = new Request4GetDeptInfo();
            request.DeptId = "";

            Response4GetDeptInfo response;
            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisWs/GetDeptInfo", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                response = responseMsg.Content.ReadAsAsync<Response4GetDeptInfo>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内GetDeptInfo Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                return null;
            }

            return response;
        }

        public Response4GetDoctorInfo GetDoctorsInHosp(string deptId)
        {
            var request = new Request4GetDoctorInfo();
            request.DeptId = deptId;
            request.DoctorId = "";

            Response4GetDoctorInfo response;

            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisWs/GetDoctorInfo", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                response = responseMsg.Content.ReadAsAsync<Response4GetDoctorInfo>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内GetDoctorInfo Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                return null;
            }

            return response;
        }
    }
}
